package cn.st4rlight.util.page;

import java.util.List;
import java.util.stream.Collectors;

import cn.st4rlight.util.collection.StreamUtil;
import cn.st4rlight.util.exception.BizAssert;
import cn.st4rlight.util.value.DefaultUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * @author st4rlight <st4rlight@163.com>
 * Created on 2024-05-04
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PageUtil {

    /**
     * 分页条件校验
     */
    public static PageRequest checkAndRewritePage(PageRequest pageRequest) {
        pageRequest = DefaultUtil.nullToDefault(pageRequest, PageRequest::new);
        BizAssert.isPositive(pageRequest.getPageSize(), "分页大小必须大于0");
        BizAssert.isPositive(pageRequest.getPageNo(), "分页页码必须大于0");
        BizAssert.isTrue(pageRequest.getPageSize() <= 100, "分页大小不能超过100");
        return pageRequest;
    }

    /**
     * 分页条件校验
     */
    public static PageRequest checkAndRewritePage(PageRequest pageRequest, int limitPageSize) {
        pageRequest = DefaultUtil.nullToDefault(pageRequest, PageRequest::new);
        BizAssert.isPositive(pageRequest.getPageSize(), "分页大小必须大于0");
        BizAssert.isPositive(pageRequest.getPageNo(), "分页页码必须大于0");
        BizAssert.isTrue(pageRequest.getPageSize() <= limitPageSize, String.format("分页大小不能超过%d", limitPageSize));
        return pageRequest;
    }

    public static <T> List<T> getPageRecords(List<T> orginList, PageRequest pageRequest) {
        return StreamUtil.safeStream(orginList)
                .skip(pageRequest.getOffset())
                .limit(pageRequest.getPageSize())
                .collect(Collectors.toList());
    }

    public static <T> List<T> getPageRecords(List<T> orginList, int pageNo, int pageSize) {
        return StreamUtil.safeStream(orginList)
                .skip((long) (pageNo - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
    }
}
